package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 上传管理接口
 */
@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    /**
     * Minio配置属性
     */
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /**
     * 上传文件
     *
     * @param file 要上传的文件
     * @return 返回上传后的文件URL
     */
    @Operation(summary = "上传文件")
    @PostMapping("/fileUpload")
    //todo 方法名记得改
    public Result findAttribute(MultipartFile file) {

        // 初始化URL为空，后续用于存储上传后的文件URL
        String url = "";
        try {
            // 构建Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                    .build();

            // 检查桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                // 如果桶不存在，则创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                // 如果桶已存在，输出提示信息
                System.out.println("Bucket "+minioConstantProperties.getBucketName()+" already exists.");
            }


            //获取文件后缀
            //创建文件名
            String fileName = UUID.randomUUID().toString().replace("-","") + file.getOriginalFilename().substring( file.getOriginalFilename().lastIndexOf("."));


            // 使用MinIO客户端进行对象上传
            minioClient.putObject(
                    PutObjectArgs.builder()
                        .bucket(minioConstantProperties.getBucketName()) // 设置存储桶名称
                        .object(fileName) // 设置对象名称
                        .stream(file.getInputStream(), file.getSize(), -1) // 设置对象的数据流、大小和分块大小
                        .contentType(file.getContentType()) // 设置对象的内容类型
                        .build()
                );

            url=minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fileName;
            // 输出上传成功信息
            System.out.println("url = " + url);

        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }

        // 返回上传后的文件URL
        return Result.ok(url);
    }

}
